<?php

namespace app\api\controller\user;

use app\api\controller\AuthController;
use app\api\service\CouponService;
use app\api\service\IntegralService;
use app\api\service\UserService;

class CouponController extends AuthController
{
    public function index()
    {
        $user_id = $this->request->user['user_id'];
        $coupon_status = $this->request->param('coupon_status',0);

        $couponList = CouponService::getUserCouponList($user_id,$coupon_status);

        return  json(['code' =>1,'data' => $couponList,'msg' => '请求成功!']);
    }

    public function redeem()
    {
        $coupon_id = $this->request->param('coupon_id',0);

        if (empty($coupon_id)){
            return json(['code' =>0, 'msg' => '非法参数!']);
        }

        $coupon = CouponService::findCoupon($coupon_id);

        if (empty($coupon)){
            return json(['code' => 0, 'msg' => '优惠券已下架!']);
        }

        if ($coupon['quota'] != -1 && $coupon['quota']<1){
            return  json(['code' =>0, 'msg' => '优惠券数量不足!']);
        }

        $user_id = $this->request->user['user_id'];

        $user_integral = IntegralService::getUserIntegral($user_id);

        if ((int)$user_integral < (int)$coupon['redeem_integral']){
            return  json(['code' =>0, 'msg' => '对不起您的积分不足!']);
        }


        $result = CouponService::redeemCoupon($user_id,$coupon);



        return $result ? json(['code' =>1,'msg' => '兑换成功!']) : json(['code' =>0,'msg' => '兑换失败!']);

    }
}